package pers.cj.pdos.controller;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import pers.cj.pdos.constant.OrderType;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.excel.ExcelGoods;
import pers.cj.pdos.excel.ExcelGoodsListener;
import pers.cj.pdos.service.*;
import pers.cj.pdos.task.CleanTempExcelTask;
import pers.cj.pdos.utils.*;
import pers.cj.pdos.vo.AttrNameVo;
import pers.cj.pdos.vo.GoodsHouseWarnVo;
import pers.cj.pdos.vo.GoodsUnitVo;
import pers.cj.pdos.vo.GoodsVo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 数据库表格操作
 */
@Controller
@RequestMapping("/goods")
public class GoodsExcelController extends BaseController {
    @Autowired
    IHouseService houseService;
    @Autowired
    IOrderRuleService orderRuleService;
    @Autowired
    ITypeService typeService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    IGoodsUnitService goodsUnitService;
    @Autowired
    IUnitService unitService;
    @Autowired
    IAttrService attrService;
    @Autowired
    IAttrNameService attrNameService;



    @RequiresPermissions("goods:insert")
    @RequestMapping("/goodsImport")
    public String goodsImport() {
        return "goods/goodsImport";
    }


    @ResponseBody
    @RequiresPermissions("goods:query")
    @RequestMapping("/goods/export")
    public ResponseData export(String status,
                               String search,
                               String typeId,
                               String no,
                               String name,
                               String attr,
                               String norms,
                               String remark,
                               String sn,
                               String houseId) {

        Company company = getCompany();
        BusinessSet businessSet = getBusinessSet();

        List<GoodsVo> list = goodsService.listVoPage(company.getId(),
                null,
                null,
                Utils.genInteger(status),
                Utils.genLikeData(search),
                typeId,
                Utils.genLikeData(no),
                Utils.genLikeData(name),
                Utils.genLikeData(attr),
                Utils.genLikeData(norms),
                Utils.genLikeData(remark),
                Utils.genBoolean(sn));


        String houseName="";
        if (Utils.isEmpty(houseId)){
            houseName = "全部仓库";
        } else {
            House house = houseService.getById(houseId);
            if (house == null) {
                return ResponseData.fail("仓库不存在");
            }
            houseName = house.getName();
        }

        String fileName = houseName + "_商品列表" + DateUtils.getDate(new Date(), DateUtils.YYYYMMDDHHMMSSSS) + ".xlsx";
        try {
            String path = FileProperUtil.getInstance().getVal("excel.temp");
            OutputStream out = new FileOutputStream(path+fileName);
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true);
            Sheet sheet1 = new Sheet(1,0, ExcelGoods.class);
            sheet1.setSheetName("商品信息");
            writer.write(genExcelGoods(businessSet, list, houseId, company), sheet1);
            writer.finish();
            out.close();
            CleanTempExcelTask.put(fileName,new Date().getTime());
            return ResponseData.success(fileName);
        } catch (IOException e) {
            return ResponseData.fail("商品列表导出失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/goods/importGoods", method = RequestMethod.POST)
    public ResponseData importGoods(MultipartFile excelFile) {

        Company company = getCompany();
        try {
            if(excelFile == null){
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }

            //文件名
            String uploadName= excelFile.getOriginalFilename();
            if (Utils.isEmpty(uploadName)) {
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }
            String type = uploadName.substring(uploadName.lastIndexOf(".")+1);
            if (!"xlsx".equals(type)){
                return ResponseData.fail("请选择'.xlsx'格式的文件");
            }

            InputStream inputStream = excelFile.getInputStream();
            ExcelGoodsListener listener = new ExcelGoodsListener();
            listener.init(company);

            TimeLog.getInstance().begin(getClass(),"读取");

            ExcelReader excelReader = new ExcelReader(inputStream, null, listener);
            excelReader.read(new Sheet(1,3, ExcelGoods.class));
            TimeLog.getInstance().end();

            TimeLog.getInstance().begin(getClass(),"保存数据");
            if (!Utils.isEmpty(listener.getGoodsList())) {
                goodsService.insert(listener.getGoodsList(), listener.getTypeList(), listener.getUnitList(), listener.getAttrList(),
                        listener.getGoodsAttrList(), listener.getGoodsUnitList(), listener.getGoodsHouseWarnList());
            }
            TimeLog.getInstance().end();

            if (Utils.isEmpty(listener.getGoodsMsgList())){
                return ResponseData.success(null);
            } else {
                ResponseData responseData = new ResponseData();
                responseData.setCode(3);
                responseData.setMsg("部分商品未导入成功");
                responseData.setData(listener.getGoodsMsgList());
                return responseData;
            }
        }  catch (Exception e) {
            return ResponseData.fail("商品导入失败");
        }

    }

    private List<ExcelGoods> genExcelGoods(BusinessSet businessSet,List<GoodsVo> goodsVoList, String houseId, Company company){
        Map<String,Integer> attrMap = new HashMap<>();
        List<AttrName> attrNameList = attrNameService.list(company.getId());

        for (int i=0;i<attrNameList.size();i++){
            attrMap.put(attrNameList.get(i).getId(), (i+1));
        }

        List<ExcelGoods> list = new ArrayList<>();
        for (GoodsVo vo : goodsVoList){
            ExcelGoods excel = new ExcelGoods();
            excel.setType(vo.getType().getName());
            excel.setNo(vo.getNo());

            excel.setName(vo.getName());
            excel.setNorms(vo.getNorms());


            for (AttrNameVo attrNameVo : vo.getAttrNameVoList()){
                int index = attrMap.get(attrNameVo.getId());
                ReflectionUtils.setFieldValue(excel, "attr"+index, attrNameVo.getAttrList().get(0).getAttrValue());
            }


            for (int i=0;i<vo.getGoodsUnitVoList().size();i++){
                String index = "";
                if(i>0){
                    index = i+"";
                }

                GoodsUnitVo goodsUnitVo = vo.getGoodsUnitVoList().get(i);

                ReflectionUtils.setFieldValue(excel, "unit"+index, goodsUnitVo.getUnit().getName());
                ReflectionUtils.setFieldValue(excel, "times"+index, goodsUnitVo.getTimes() + "");
                ReflectionUtils.setFieldValue(excel, "code"+index, goodsUnitVo.getCode());
                ReflectionUtils.setFieldValue(excel, "retailPrice"+index, goodsUnitVo.getRetailPrice());
                ReflectionUtils.setFieldValue(excel, "wholesalePrice"+index, goodsUnitVo.getWholesalePrice());
                ReflectionUtils.setFieldValue(excel, "minPrice"+index, goodsUnitVo.getMinPrice());
                ReflectionUtils.setFieldValue(excel, "referBuyPrice"+index, goodsUnitVo.getReferBuyPrice());
            }

            double houseWarnMin = 0;
            double houseWarnMax = 0;
            for (GoodsHouseWarn goodsHouseWarn : vo.getGoodsHouseWarnList()){
                if(Utils.isEmpty(houseId) || (!Utils.isEmpty(houseId) && houseId.equals(goodsHouseWarn.getHouseId()))) {
                    houseWarnMin += goodsHouseWarn.getMin().doubleValue();
                    houseWarnMax += goodsHouseWarn.getMax().doubleValue();
                }
            }

            if (Utils.isInt(houseWarnMin+"")) {
                excel.setHouseWarnMin((int)houseWarnMin+"");
            } else {
                excel.setHouseWarnMin(Utils.getFloatStr(houseWarnMin, businessSet.getNumPoint()));
            }

            if (Utils.isInt(houseWarnMax+"")) {
                excel.setHouseWarnMax((int)houseWarnMax+"");
            } else {
                excel.setHouseWarnMax(Utils.getFloatStr(houseWarnMax, businessSet.getNumPoint()));
            }

            excel.setStatus(vo.getStatus()==1 ? "启用":"停用");
            excel.setRemark(vo.getRemark());
            list.add(excel);
        }

        return list;
    }
}
